package components

import (
	"eino-script/engine/components/tools"
	"eino-script/engine/entity"
	"eino-script/engine/types"
	"fmt"
	"github.com/cloudwego/eino/compose"
)

type McpToolNode struct {
	types.Node
}

func (mt McpToolNode) Id() string {
	return mt.Node.Id
}

func (mt McpToolNode) Type() (entity.NodeType, error) {
	return mt.Node.Type, nil
}

func (mt *McpToolNode) GetTargetId() (string, error) {
	return mt.Node.Id, nil
}

func (mt *McpToolNode) GetSourceId() (string, error) {
	return mt.Node.Id, nil
}

func CreateMcpToolNode(cfg *entity.Node, g *compose.Graph[any, any], callbacks types.Callbacks) (types.NodeInterface, error) {
	n, err := CreateGeneralNode(cfg)
	if err != nil {
		return nil, err
	}

	node := &McpToolNode{
		Node: *n,
	}

	id := node.Id()
	if id == "" {
		return nil, err
	}

	mcpId := cfg.GetValue("inputsValues.mcpId").Value().(float64)
	if mcpId == 0 {
		return nil, fmt.Errorf("McpTool的mcpId没有设置。")
	}

	server, err := callbacks.Callback_CreateMcpServer(uint(mcpId))
	if err != nil {
		return nil, err
	}

	mcpTool, err := tools.CreateMcpToolNode(cfg, server)
	if err != nil {
		return nil, err
	}

	//Todo: 对齐问题还需要处理
	err = g.AddToolsNode(id, mcpTool, compose.WithOutputKey("outmessage"))
	if err != nil {
		return nil, err
	}

	return node, nil
}
